package com.groupware.message.mybatis;

import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.groupware.message.Vo.MessageVo;

public class MessageManager {

	  private static SqlSessionFactory sqlMapper;
	  
	   static {
	      try {
	         Reader reader = Resources
	               .getResourceAsReader("com/groupware/message/mybatis/SqlMapConfig.xml");
	         sqlMapper = new SqlSessionFactoryBuilder().build(reader);
	         reader.close();
	      } catch (IOException e) {
	         throw new RuntimeException(
	               "Something bad happened while building the SqlMapClient instance."
	                     + e, e);
	      }
	   }
	public static String getSender(String userName) {
		SqlSession session = sqlMapper.openSession();		
		String name = session.selectOne("getSender", userName);
		session.close();
		return name;
	}

	public static void insertMessage(MessageVo vo) {
		SqlSession session = sqlMapper.openSession();		
		session.insert("insertMessage",vo);
		session.commit();
		session.close();
	}
	
	public static List<MessageVo> getList(){
		SqlSession session = sqlMapper.openSession();		
		List<MessageVo> list = session.selectList("getlist");
		session.close();
		return list;
	}
	public static MessageVo getmessage(String receiver){
		SqlSession session = sqlMapper.openSession();		
		MessageVo vo= session.selectOne("getmessage",receiver);
		System.out.println(receiver);
		session.close();
		return vo;
	}
	
	public static List<MessageVo> getReceiveMail(String userName){
		SqlSession session = sqlMapper.openSession();		
		List<MessageVo> list = session.selectList("getreceivemail",userName);
		session.close();
		return list;
	}
	public static List<MessageVo> getSendMail(String userName){
		SqlSession session = sqlMapper.openSession();		
		List<MessageVo> list = session.selectList("getsendmail",userName);
		session.close();
		return list;
	}
	
	public static List<MessageVo> getPage(int start, int end){
		SqlSession session = sqlMapper.openSession();
		HashMap<String,Object> map = new HashMap<String,Object>();
		map.put("start",start);
		map.put("end",end);
		List<MessageVo> list = session.selectList("getpage",map);
		session.close();
		return list;
	}
	

public static int getCount(){
	SqlSession session = sqlMapper.openSession();		
	int count= session.selectOne("getcount");
	session.close();
	return count;
}

}
